//
//  OauthViewController.swift
//  WeiBo001
//
//  Created by ZhiQiang Li on 16/7/21.
//  Copyright © 2016年 ZhiQiang Li. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class OauthViewController: UIViewController {

    override func loadView() {
        // 请求的url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        // 初始化一个url
        let url = NSURL(string: urlString)
        guard let u = url else{
            return
        }
        // 初始化一个request
        let request = NSURLRequest(URL: u)
        // webView 加载requet
        webView.loadRequest(request)
        webView.delegate = self
        view = webView
        
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        progressView.removeView()
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    
    // - 监听事件
    @objc private func cancelClick(){
        // 关闭控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFillClick(){
        print("自动填充按钮")
        let jsString = "document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPasswd)'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    //  - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
        setupNav()
    }
    
    
    
    // : - 设置导航
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imgName: nil, target: self, action: "autoFillClick")
        navigationItem.title = "微博登录"
    }
    
    // : - 懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    // webView进度条
    private lazy var progressView: OauthProgressView = OauthProgressView()
    
}


extension OauthViewController: UIWebViewDelegate {
    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
         progressView.startAnim()
        // SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //  SVProgressHUD.dismiss()
       progressView.endAnim()
    }
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 请求的url字符串
        let urlString = request.URL?.absoluteString
        // 判断urlString 是否为nil 而且他的前缀为回调页
        if let u = urlString where u.hasPrefix(APPREDIRECT_URI) {
            // url 的请求参数
            let query = request.URL?.query
            if let q = query {
                // 获取code
                let code = q.substringFromIndex("code=".endIndex)
                print("哈哈哈哈哈:\(code)")
                
              CZUserAccountViewModel.sharedTools.loadUserAccount(code, isSuccess: { (isSucc) -> () in
                print(isSucc)
                
                if !isSucc {
                    print("请求失败")
                    return

                }
                
                // 先关闭当前界面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    // 发送一个通知 告知appdelegate 切换根控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                })
                
              })
                return false
                
                
  
    
            }
            

        }
        return true
    }

}


//请求数据
extension OauthViewController {
    // 请求accessToken
    func getUserAccount(code: String){
        
       CZNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
            // 当在guard 或者if let中 使用as  一般情况下 都是使用as?
            // 判断response是否为nil 而且是否可以转成字典
            guard let res = response as? [String: AnyObject] else{
                return
            }
            // 字典转模型
            let userAccount = CZModel(dict: res)
            self.getUserInfo(userAccount)
            }) { (error) -> () in
                print("请求失败\(error)")
        }
        
        
    }

    // 获取用户信息数据
    func getUserInfo(userAccount: CZModel){
        
        CZNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            // 判断response是否为nil 而且是否可以转成字典
            guard let res = response as? [String: AnyObject] else{
                return
            }
                       // 给其userAccount身上两个为nil的属性赋值
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
            print(userAccount)
            }) { (error) -> () in
                print("请求失败:\(error)")

    
    
    
        }
        
    }
    
    
}











